package com.jsm.tf.net;

import com.google.common.cache.*;
import com.jsm.tf.director.Director;
import com.jsm.tf.net.handler.IdleStateEventHandler;
import com.jsm.tf.net.handler.ResponseMessageHandler;
import com.jsm.tf.net.message.Message;
import com.jsm.tf.net.message.ResponseMessage;
import com.jsm.tf.net.protocol.MessageCodec;
import com.jsm.tf.net.protocol.ProtocolFrameDecoder;
import com.jsm.tf.net.protocol.serialize.Serializer;
import com.jsm.tf.net.sync.SyncFuture;
import com.jsm.tf.view.dialog.TFDialog;
import de.felixroske.jfxsupport.GUIState;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;


@Component
@Slf4j
public class NettyClient {
    public static final LoggingHandler LOGGING_HANDLER = new LoggingHandler();
    //缓存接口这里是LoadingCache，LoadingCache在缓存项不存在时可以自动加载缓存
    private static LoadingCache<Long, SyncFuture> futureCache = CacheBuilder.newBuilder()
            //设置缓存容器的初始容量为10
            .initialCapacity(100)
            // maximumSize 设置缓存大小
            .maximumSize(10000)
            //设置并发级别为20，并发级别是指可以同时写缓存的线程数
            .concurrencyLevel(20)
            // expireAfterWrite设置写缓存后8秒钟过期
            .expireAfterWrite(8, TimeUnit.SECONDS)
            //设置缓存的移除通知
            .removalListener(new RemovalListener<Object, Object>() {
                @Override
                public void onRemoval(RemovalNotification<Object, Object> notification) {
                    log.debug("LoadingCache: {} was removed, cause is {}", notification.getKey(), notification.getCause());
                }
            })
            //build方法中可以指定CacheLoader，在缓存不存在时通过CacheLoader的实现自动加载缓存
            .build(new CacheLoader<Long, SyncFuture>() {
                @Override
                public SyncFuture load(Long key) throws Exception {
                    // 当获取key的缓存不存在时，不需要自动添加
                    return null;
                }
            });
    @Value("${netty.sync.time-out:5000}")
    public int syncTimeout;
    private AtomicLong seqBuilder = new AtomicLong(0);
    @Resource
    private RpcSyncPromise rpcSyncPromise;
    @Resource
    private Serializer serializer;
    @Value("${netty.client.heartbeat.interval:5}")
    private int heartbeatInterval;
    @Resource
    private Director director;
    @Resource
    private ResponseMessageHandler responseMessageHandler;
    private EventLoopGroup group = new NioEventLoopGroup();
    /**
     * @Fields hostIp : 服务端ip
     */
    @Value("${netty.server.ip:127.0.0.1}")
    private String hostIp;
    /**
     * @Fields port : 服务端端口
     */
    @Value("${netty.server.port:8888}")
    private int port;
    /**
     * @Fields socketChannel : 通道
     */
    private SocketChannel socketChannel;
    @Resource
    private IdleStateEventHandler idleStateEventHandler;


    @PostConstruct
    public void start() {

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                // 指定Channel
                .channel(NioSocketChannel.class)
                // 服务端地址
                .remoteAddress(hostIp, port).option(ChannelOption.SO_KEEPALIVE, true)
                // 将小的数据包包装成更大的帧进行传送，提高网络的负载,即TCP延迟传输
                .option(ChannelOption.TCP_NODELAY, true)
                //链接超时时长
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000).handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProtocolFrameDecoder());
                        ch.pipeline().addLast(LOGGING_HANDLER);
                        ch.pipeline().addLast(new MessageCodec(serializer));
                        ch.pipeline().addLast(new IdleStateHandler(0, heartbeatInterval, 0));
                        //ChannelDuplexHandler可以同时作为入站和出站处理器
                        ch.pipeline().addLast(idleStateEventHandler);
                        ch.pipeline().addLast(responseMessageHandler);
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        Channel channel = ctx.channel();
                        director.setChannel(channel);
                        super.channelActive(ctx);
                    }
                });

        // 连接
        try {
            ChannelFuture channelFuture = bootstrap.connect().sync();
            socketChannel = (SocketChannel) channelFuture.channel();
        } catch (Exception e) {
            log.error("！！！！！连接服务器异常！！！！！！");
            e.printStackTrace();
        }
//        //客户端断线重连逻辑
//        channelFuture.addListener(new ChannelFutureListener() {
//
//            @Override
//            public void operationComplete(ChannelFuture future) throws Exception {
//                if (future.isSuccess()) {
//                    log.info("连接Netty服务端成功...");
//                } else {
//
//                    log.info("连接Netty服务端失败，进行断线重连...");
//                    final EventLoop loop = future.channel().eventLoop();
//                    loop.schedule(new Runnable() {
//                        @Override
//                        public void run() {
//                            log.info("连接正在重试...");
//                            start();
//                        }
//                    }, 1000, TimeUnit.SECONDS);
//                }
//            }


//        });


    }

    public void sendMsg(Message message) {
        message.setSeq(seqBuilder.getAndIncrement());
        socketChannel.writeAndFlush(message);
    }

    public <T extends ResponseMessage> T sendSyncMsg(Message<T> message) {
        message.setSeq(seqBuilder.getAndIncrement());
        socketChannel.writeAndFlush(message);
        T response = (T) rpcSyncPromise.sync(Message.commandClassMap.get(message.getCommandType()), message.getSeq(), socketChannel.eventLoop());
        if (!response.isSuccess()) {
            TFDialog.showConfirmDialog(GUIState.getStage(), response.getErrorMsg(), "错误");
        }
        return response;
    }

    public void ackSyncMsg(Message msg) {
        rpcSyncPromise.ack(msg.getSeq(), msg);
    }

    @PreDestroy
    public void PreDestroy() throws InterruptedException {
        group.shutdownGracefully().sync();
        if (director.getChannel() != null) {
            director.getChannel().close();
        }
        log.info("关闭Netty...");
    }
}
